package io.bdmc.modules.api.controller;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.jms.Destination;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import org.apache.activemq.command.ActiveMQQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import io.bdmc.common.http.AIResponse;
import io.bdmc.common.http.ZxyHttpUtil;
import io.bdmc.common.nbapi.sdk.analyze.ParsingMessage;
import io.bdmc.common.utils.ExcelImport;
import io.bdmc.common.utils.R;
import io.bdmc.modules.api.annotation.AuthIgnore;
import io.bdmc.modules.api.service.ProducerService;
import io.bdmc.modules.bss.entity.SmkMessage;
import io.bdmc.modules.bss.model.alarm.AlarmHKData;
import io.bdmc.modules.bss.model.alarm.MessageHKData;
import io.bdmc.modules.bss.service.ISmkMessageService;
import io.bdmc.modules.bss.service.ISmkShopService;

@RestController
@RequestMapping(value = "/msg")
public class MessageController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private ISmkMessageService _msglogSvs;

    @Resource
    ProducerService _producerSvs;

    @Resource
    ISmkShopService _shopSvs;

    @Resource
    ZxyHttpUtil _zxyUtil;

    @AuthIgnore
    @PostMapping(value = "/ct")
    public R ctmsg(@RequestBody(required = false)  MessageHKData message) {

        AlarmHKData alarm = ParsingMessage.analysis_Smoke_Msg(message.getMsg().getValue());
        //{"msg":{"at":1584596471451,"imei":"861566040761387","type":1,"ds_id":"3339_0_5522","value":"07aa8200000000000013090c000000671200ffc00009000000003839383630343530313631393930313737303030ad","dev_id":588476371},"msg_signature":"0vj7sW2iY4Txw0BJLZ0nLA==","nonce":"I1k!e4tW"}
        // double[] latlng = CoordTransform.transformWGS84ToGCJ02(113.30263,22.2156);

        // Integer objId = 3200;
        // Integer objInstId = 0;
        // Integer readResId = 5500;
        // Integer executeResId = 5501;
        // Integer writeResId = 5750;
        // Integer writeMode = 2;
        // Create device
        // _zxyUtil.setPushPath("http://xf.ctjt.cn:8099/smokev2/msg/zxy");
        // 设备火警{"deviceLoopId":"1","deviceType":"76","flag":3,"deviceGroupState":"1","gatewayName":"01_TX3251_123456789","devicePosition":"商店","deviceId":"0f063102-6600-4403-9418-3c4b73678a8b","deviceNumber":"089326589365","deviceAddrId":"1","pushType":"1","logId":"e93886dc-b68b-40e3-ac0d-72865574ea75","deviceState":"1","deviceControllerId":"1","projectId":"6d674e7c760842a1aac084ef00f099a2","deviceChannelId":"1","happenTime":"1526711088000"}
        // 故障{"deviceLoopId":"1","deviceType":"76","flag":3,"deviceGroupState":"2","gatewayName":"01_TX3251_123456789","devicePosition":"商店","deviceId":"0f063102-6600-4403-9418-3c4b73678a8b","deviceNumber":"089326589365","deviceAddrId":"1","pushType":"1","logId":"e93886dc-b68b-40e3-ac0d-72865574ea75","deviceState":"20","deviceControllerId":"1","projectId":"6d674e7c760842a1aac084ef00f099a2","deviceChannelId":"1","happenTime":"1526711088000"}
        // 控制器故障{"deviceType":"76","flag":1,"deviceGroupState":"2","gatewayName":"01_TX3251_123456789","devicePosition":"商店","logId":"e93886dc-b68b-40e3-ac0d-72865574ea75","deviceState":"20","deviceControllerId":"1","projectId":"6d674e7c760842a1aac084ef00f099a2","deviceId":"0f063102-6600-4403-9418-3c4b73678a8b","happenTime":"1526711088000","pushType":"1"}
        // 消音{"deviceLoopId":"9999","deviceType":"78","flag":2,"deviceGroupState":"","gatewayName":"01_NB_18082701010101243078","devicePosition":"","deviceId":"0e91517a65de479ca58ddb7f280b8ad4","deviceNumber":"18082701010101243078","deviceAddrId":"9999","pushType":"2","optCode":"2","logId":"f02888d1044f46a3a7ff5fe26e1568f0","deviceState":"","deviceControllerId":"0","projectId":"6d674e7c760842a1aac084ef00f099a2","deviceChannelId":"9999","happenTime":"1565081133472"}
        // 火警{"deviceLoopId":"9999","deviceType":"78","flag":2,"deviceGroupState":"1","gatewayName":"01_NB_18082701010101243078","devicePosition":"","deviceId":"0e91517a65de479ca58ddb7f280b8ad4","deviceNumber":"18082701010101243078","deviceAddrId":"9999","pushType":"1","optCode":"","logId":"d2b4279c74d745bfbe6cbe387d033a7e","deviceState":"1","deviceControllerId":"0","projectId":"6d674e7c760842a1aac084ef00f099a2","deviceChannelId":"9999","happenTime":"1565081126746"}
        // 上线{"deviceLoopId":"0","deviceType":"0","flag":0,"deviceGroupState":"","gatewayName":"01_NB_18082701010101243078","devicePosition":"null","deviceId":"e6236c5396384c34b6851cfa71645548","deviceNumber":"-","deviceAddrId":"0","pushType":"2","optCode":"1","logId":"85ad498688674edca8c244bbde532089","deviceState":"","deviceControllerId":"0","projectId":"6d674e7c760842a1aac084ef00f099a2","deviceChannelId":"0","happenTime":"1565081882264"}
        // 拆卸{"deviceLoopId":"9999","deviceType":"78","flag":2,"deviceGroupState":"2","gatewayName":"01_NB_18082701010101243078","devicePosition":"","deviceId":"0e91517a65de479ca58ddb7f280b8ad4","deviceNumber":"18082701010101243078","deviceAddrId":"9999","pushType":"1","optCode":"","logId":"6430b083367346e294c7d681bbf82ed9","deviceState":"150","deviceControllerId":"0","projectId":"6d674e7c760842a1aac084ef00f099a2","deviceChannelId":"9999","happenTime":"1565081916473"}
        return R.ok();
    }

    @AuthIgnore
    @PostMapping(value = "/zxy")
    public R zxy(@RequestBody String json) {
        if (!StringUtils.isEmpty(json)) {
            logger.info(json);
        }
        Destination destination = new ActiveMQQueue("zxy.queue");
        _producerSvs.sendMessage(destination, json);
        return R.ok();
    }

    @AuthIgnore
    @PostMapping(value = "/hk") // 海康
    public R hk(@RequestBody(required = false) String json) {
        if (!StringUtils.isEmpty(json)) {
            logger.info(json);
        }
        Destination destination = new ActiveMQQueue("hk.queue");
        _producerSvs.sendMessage(destination, json);
        return R.ok();
    }

    @AuthIgnore
    @GetMapping(value = "/hk") // 海康验证接口
    public String hk1(String msg, String nonce, String signature) {
        // msg=x&nonce=y&signature=z
        return msg;
    }

    @AuthIgnore
    @PostMapping(value = "/aiTest")
    public R aiTest(@RequestBody(required = false) String json) {
        if (!StringUtils.isEmpty(json)) {
            logger.info(json);
        }
        // String details = "尊敬的测试用户，您位于%s的%s发生火灾告警，请尽快确认情况,及时处理";
        // String[] args = new String[]{"武汉市光谷科技港","黄焖鸡店铺"};
        // _smsSvs.voiceSendSingle("18602720906", 11, args, details, "appId",
        // "appSecret");
        // logger.info("发生语音给：" + mobile + "。请求返回结果：" + ss);
        return R.ok();
    }

    // {"msg":"ok","data":{"number":"18814187583","openId":"19091786483973177344","bill":3160,"hangupcause":"NORMAL_CLEARING",
    // "hangupdate":"2019-09-17
    // 11:27:21","content":"你好，这里是语音播报平台","taskId":"19080683537258610688"},"status":200}
    @AuthIgnore
    @PostMapping(value = "/ai") // 接收ai语音回调
    public R aiMsg(@RequestBody(required = false) String json) {
        if (!StringUtils.isEmpty(json)) {
            logger.info(json);
        }
        AIResponse resp = JSONObject.parseObject(json, AIResponse.class);
        String callid = resp.getData().getString("openId");
        if (StringUtils.isEmpty(callid)) {
            return R.error(-1, "openId为空");
        }
        QueryWrapper<SmkMessage> w1 = new QueryWrapper<SmkMessage>();
        w1.eq("callid", callid);
        SmkMessage msg = _msglogSvs.getOne(w1);
        if (msg != null) {
            msg.setResultCode("0");
            msg.setResultMsg(resp.getMsg());
            msg.updateById();
        }

        return R.ok();
    }

    @AuthIgnore
    @PostMapping(value = "/handler")
    public R handler(@RequestBody String json) {
        try {
            // _httpSvs.doPostJson("http://hexiaofang.com:8090/smokev2/msg/handler", json);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage() + e.toString());
        }
        Destination destination = new ActiveMQQueue("3jadmin.queue");
        _producerSvs.sendMessage(destination, json);
    
        return R.ok();
    }


    @AuthIgnore
	@PostMapping("download")
	// @RequiresPermissions("bss:shop:import")
	// @ApiOperation(value = "导入Excel",notes = "将数据以Excel的形式导入到数据库中")
	public R downloadPic(@RequestParam("file") MultipartFile file) throws Exception {
		// 获取用户上传表格的地址，执行完程序后表格将会删除，避免占用内存
		// 根据地址和文件名准确获取用户上传的表格
		// File tempFile = new File(file.getInputStream());
		try {
			// 将MultipartFile转换为File类型
			// file.transferTo(tempFile);
			String fileName = file.getOriginalFilename();
			String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
			InputStream in = file.getInputStream();
			List<Map<String, String>> dataList = ExcelImport.read(in, suffix);
            String folder = fileName.replace(".xlsx", "");
			for (int i = 0; i < dataList.size(); i++) {
				String duty = dataList.get(i).get("duty_letter");
				String picture = dataList.get(i).get("picture");
				if (!StringUtils.isEmpty(duty)) {
					String url = "http://xf.ctjt.cn:8090/smokev2" + duty;
					String newfileName = "d:/test/"+folder +"/"+ dataList.get(i).get("shop_name") + ".jpg";
					downloadPicture(url, newfileName);
				}
				if (!StringUtils.isEmpty(picture)) {
					String url = "http://xf.ctjt.cn:8090/smokev2" + picture;
					String newfileName = "d:/test/"+folder +"/"+ dataList.get(i).get("shop_name") + ".jpg";
					downloadPicture(url, newfileName);
				}
			}

			// 加入实时表
			return R.ok();
		} catch (Exception e) {
			// tempFile.delete();
			// throw new Exception("批量录入用户失败，请检查表格中的数据是否和数据库中的数据冲突！");
			e.printStackTrace();
			return R.error("导入失败，请检查表格中的数据");
		}
	}

	private void downloadPicture(String urlList, String imageName) {
		URL url = null;
		try {
			url = new URL(urlList);
            DataInputStream dataInputStream = new DataInputStream(url.openStream());
            String folder =  imageName.substring(0,imageName.lastIndexOf("/"));
            File d = new File(folder);
			if (!d.exists()) {
				d.mkdir();
			}
			File f = new File(imageName);
			if (!f.exists()) {
				f.createNewFile();
			}
			FileOutputStream fileOutputStream = new FileOutputStream(f);
			ByteArrayOutputStream output = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int length;
			while ((length = dataInputStream.read(buffer)) > 0) {
				output.write(buffer, 0, length);
			}
			byte[] context = output.toByteArray();
			fileOutputStream.write(context);
			dataInputStream.close();
			fileOutputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}